package com.gary.spring;

import com.gary.spring.bean.Bean1;
import com.gary.spring.bean.Bean2;
import com.gary.spring.bean.Bean3;
import com.gary.spring.bean.Bean4;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.context.support.GenericApplicationContext;

/**
 * @author peng_rui
 * @date 2022/6/21
 */
@SpringBootApplication
@ConfigurationPropertiesScan
public class StudyMain {
    public static void main(String[] args) {
//        ConfigurableApplicationContext context = SpringApplication.run(StudyMain.class, args);
//        context.close();

        //GenericApplicationContext 一个【干净】的容器
        GenericApplicationContext context = new GenericApplicationContext();

        //使用原始方法注入bean
        context.registerBean("bean1", Bean1.class);
        context.registerBean("bean2", Bean2.class);
        context.registerBean("bean3", Bean3.class);
        context.registerBean("bean4", Bean4.class);

        context.getDefaultListableBeanFactory().setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());

        /**
         *  name 'bean1': Unsatisfied dependency expressed through method 'autoValue' parameter 0;
         *  异常原因：使用了@Value 因此 在注入AutowiredAnnotationBeanPostProcessor 需要修改Resolver
         */
        //@Autowired @Value
        context.registerBean(AutowiredAnnotationBeanPostProcessor.class);

        //@Resource @PostConstruct @PreDestroy
        context.registerBean(CommonAnnotationBeanPostProcessor.class);

        //@ConfigurationProperties(prefix = "java")
        ConfigurationPropertiesBindingPostProcessor.register(context.getDefaultListableBeanFactory());

        // 初始化容器：执行beanFactory后处理器，添加bean后处理器， 初始化所有单例
        context.refresh();

        Bean4 bean = context.getBean(Bean4.class);
        System.out.println(bean);

        context.close();
    }
}
